#ifndef __MY_CONFIG__
#define __MY_CONFIG__
#include <mutex>
#include "fileUtil.hpp"
#include "jsonUtil.hpp"

namespace cloudBackup
{
#define CONFIG_FILE "./cloudBackup.conf"
	class Config
	{
	private:
		// 单例类设计
		static Config *_instance;
		static std::mutex _mutex;

		// 配置类主要字段
		int _hotTime;				   // 判定热点文件时间间隔
		std::string _serverIp;		   // 服务器监听/绑定哪个IP
		int _serverPort;			   // 服务器监听端口
		std::string _urlDownloadID;	   // http请求下载字段标识  /download/
		std::string _zipSuffix;		   // 压缩包后缀
		std::string _zipDir;		   // 压缩包存放路径 非热点文件存放路径
		std::string _backupDir;		   // 云备份文件存放路径 热点文件存放路径
		std::string _backupAInfoFName; // 存放 已备份文件属性信息 的文件名

		// 读取配置文件
		bool ReadConfigFile()
		{
			FileUtil fileUtil(CONFIG_FILE);
			std::string content;
			// 获取整个文件内容传递给content
			if (fileUtil.GetContent(&content) == false)
			{
				Log::log(LOGERROR, "Config::ReadConfigFile::fileUtil.GetContent() failed !: %s: %d", strerror(errno), errno);
				return false;
			}

			// 字符串反序列化成json对象
			Json::Value root;
			if (JsonUtil::Deserialize(content, &root) == false)
			{
				Log::log(LOGERROR, "Config::ReadConfigFile::JsonUtil::Deserialize() failed !: %s: %d", strerror(errno), errno);
				return false;
			}

			_hotTime = root["hotTime"].asInt();
			_serverPort = root["serverPort"].asInt();
			_serverIp = root["serverIp"].asString();
			_urlDownloadID = root["urlDownloadID"].asString();
			_zipSuffix = root["zipSuffix"].asString();
			_zipDir = root["zipDir"].asString();
			_backupDir = root["backupDir"].asString();
			_backupAInfoFName = root["backupAInfoFName"].asString();

			FileUtil tmp1(_backupDir);
			FileUtil tmp2(_zipDir);
			tmp1.CreateDirectory();
			tmp2.CreateDirectory();
			
			Log::log(INFO, "Config::ReadConfigFile success!");
			return true;
		}

		Config()
		{
			ReadConfigFile();
		}

	public:
		// 懒汉模式 用的时候再创建实例
		static Config *GetInstance()
		{
			if (_instance == NULL)
			{
				_mutex.lock();
				if (_instance == NULL)
					_instance = new Config();
				_mutex.unlock();
			}
			return _instance;
		}

		int GetHotTime()
		{
			return _hotTime;
		}

		int GetServerPort()
		{
			return _serverPort;
		}

		std::string GetServerIp()
		{
			return _serverIp;
		}

		std::string GetUrlDownloadID()
		{
			return _urlDownloadID;
		}

		std::string GetZipSuffix()
		{
			return _zipSuffix;
		}

		std::string GetZipDir()
		{
			return _zipDir;
		}

		std::string GetBackupDir()
		{
			return _backupDir;
		}

		std::string GetBackupAInfoFName()
		{
			return _backupAInfoFName;
		}
	};
	/*类内声明 类外初始化
	static Config *_instance;
	static std::mutex _mutex;
	*/
	Config *Config::_instance = NULL;
	std::mutex Config::_mutex;
}

#endif //__MY_CONFIG__
